<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="100">
            <div v-if="switchFlag">
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                        <FormItem label="上报人：" >
                            <Input type="text" v-model="form1.userName"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="上报时间：">
                            <DatePicker v-model="form1.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择上报时间范围"></DatePicker>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="流程名称：">
                            <Select v-model="form1.procinstName" filterable>
                                <Option v-for="item in workFlowList" :value="item.text">{{item.text}}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>

                <Row :gutter="16" class="query-form2">
                    <i-col span="24">
                        <div style="float: right;">
                            <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                            <Button @click="reset" class="ivu-btn-reset" style="margin-left: 10px" >重置</Button>
                            <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text" >收起<Icon type="ios-arrow-up" /></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
            <div v-else>
                <Row :gutter="16" class="query-form2">
                    <i-col span="8">
                        <FormItem label="上报人：" prop="userName">
                            <Input type="text" v-model="form1.userName"/>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <FormItem label="上报时间：" prop="se_date">
                            <DatePicker v-model="form1.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择上报时间范围"></DatePicker>
                        </FormItem>
                    </i-col>
                    <i-col span="8">
                        <div style="float: right;">
                            <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                            <Button @click="reset" class="ivu-btn-reset" style="margin-left: 10px" >重置</Button>
                            <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text" >展开<Icon type="ios-arrow-down"/></Button>
                        </div>
                    </i-col>
                </Row>
            </div>
        </Form>
        <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" :loading="loading"
               border :columns="columns1"  :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24" >
                <Page style="float: right" :total="pagedata.total"  :current="pagedata.currentPage"  :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal :transfer=false footer-hide v-model="model1"  :width=900>
            <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!"
                   border :columns="columns2"  :data="history">
            </Table>
        </Modal>
        <Modal title="流程图" :transfer=false footer-hide v-model="model2"  :width=900>
            <img :src="imgUrl" style="width: 100%; height: 100%">
        </Modal>
        <Modal title="流程补救" :transfer=false v-model="model3"  :width=900>
            <Form :label-width="130" ref="formCustom" :model="form1data" :rules="ruleCustom">
                <Row :gutter="16">
                    <i-col span="24">
                        <FormItem label="当前节点：" prop="oldUserId">
                            <Select label-in-value v-model="form1data.oldUserId" @on-change="changeType">
                                <Option v-for="item in taskType" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="24">
                        <FormItem label="当前执行人：" prop="oldUserName">
                            <Input type="text" v-model="form1data.oldUserName" readonly/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row :gutter="16">
                    <i-col span="24">
                        <FormItem label="指定补救人：" prop="newUserId">
                            <Input class='' placeholder="请选择补救人" type='text' v-model='form1data.newUserName' @on-focus="openSelect"></Input>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button @click="canal()" class='ivu-btn-cancel' style="margin-left: 8px">关闭</Button>
                <Button @click="assignSubmit()" class='ivu-btn-save'  :loading="loading3">提交</Button>
            </div>
        </Modal>

        <UserForTaskSelect :usersListModal="usersListModal" @closeDialog="closeDialog" @getSelectData="setPeople">
        </UserForTaskSelect>
        <Modal :transfer=false v-model="model4"  :width=900  footer-hide>

            <router-view :to="{ path: path, data: routeData }" style="height: 600px">{{path}}</router-view>
        </Modal>


        <Modal :transfer=false v-model="historyModal" :width=900>
            <Tabs>
                <TabPane label="历史记录">
                    <Table ref='table' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                           :loading="loading2"
                           :data="history" width="100%" :height="450" highlight-row stripe size="small"></Table>
                </TabPane>
                <TabPane label="流程图">
                    <div style="height: 450px; overflow-y: auto; overflow-x: auto">
                        <img :src="imgUrl">
                    </div>
                </TabPane>
                <TabPane label="人员变更记录">
                    <Table ref='table' border :columns="columns3" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                           :loading="loading2"
                           :data="historyChange" width="100%" :height="450" highlight-row stripe size="small"></Table>
                </TabPane>
            </Tabs>
            <div slot="footer">
                <Button @click="historyModal=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>

    </Layout>
</template>

<script>

    import {Api} from '../../../api/index.js'
    import { sessionStorage, cookie } from '../../../common/cacheUtils.js';
    import cascaderDom from '../../../components/cascader-dom.vue'
    import UserForTaskSelect from './userForTaskSelect.vue'

    export default {
        components: {
            cascaderDom,
            UserForTaskSelect
        },
        data(){
            return{
                loading3: false,
                loading2: false,
                historyModal: false,
                path: '',
                routeData: {},
                switchFlag: false,
                form1:{
                    se_date: [],
                    userName:""
                },
                usersListModal:false,
                imgUrl: '',
                loading: false,
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                columns1: [
                    {
                        type: 'index',
                        title: '序号',
                        minWidth: 80,
                        align: 'center',
                    },
                    {
                        minWidth: 250,
                        title: '流程名称',
                        align: 'center',
                        key: 'procinstName',
                    },
                    {
                        minWidth: 150,
                        title: '流程状态',
                        key: 'procinstStateName',
                        align: 'center',
                    },
                    {
                        minWidth: 210,
                        title: '上报时间',
                        key: 'createDate',
                        align: 'center',
                        render:(h,params)=>{
                            return h('div',[
                                (this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd hh:mm:ss'))
                            ]);
                        }
                    },
                    {
                        minWidth: 210,
                        title: '上报人',
                        key: 'userName',
                        align: 'center'
                    },
                    {
                        minWidth: 200,
                        title: '当前任务节点名称',
                        key: 'taskName',
                        align: 'center'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 280,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.showData(params.row);
                                        }
                                    }
                                }, '详情'),
                                  h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        marginLeft:"8px"
                                    },
                                    on: {
                                        click: () => {
                                            this.flowRemedy(params.row);
                                        }
                                    }
                                }, '补救'),
                                  h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        marginLeft: '8px',
                                        color: 'red'
                                    },
                                    on: {
                                        click: () => {
                                            this.shopWorkflow(params.row);
                                        }
                                    }
                                }, '终止'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        marginLeft: '8px'
                                    },
                                    on: {
                                        click: () => {
                                            this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                            this.showHistory(params.row);
                                        }
                                    }
                                },'审批记录'),
                                //   h('Divider', {
                                //     props: {
                                //         type: 'vertical',
                                //     }
                                // }, ''),
                                // h('A', {
                                //     props: {
                                //         type: 'primary',
                                //         size: 'small'
                                //     },
                                //     style: {
                                //         fontSize: '14px',
                                //         marginLeft: '8px'
                                //     },
                                //     on: {
                                //         click: () => {
                                //             this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                //             this.model2 = true;
                                //         }
                                //     }
                                // },'流程图')
                        ]);
                    }
                }
                ],
                dataTable: [],
                tableHeight : 10,
                model1 : false,
                model2 : false,
                model3 : false,
                model4 : false,
                history : [],
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        width: 180,
                        title: '审批时间',
                        key: 'endTime',
                        align: 'center',
                    },
                    {
                        width: 185,
                        title: '节点名称',
                        key: 'name',
                        align: 'center',
                    },
                    {
                        width: 120,
                        title: '审批人',
                        key: 'userName',
                        align: 'center'
                    },
                    {
                        width: 100,
                        title: '审批意见',
                        key: 'route',
                        align: 'center'
                    },
                    {
                        width: 200,
                        title: '备注',
                        key: 'opinions',
                        align: 'center'
                    },
                ],
                form1data: {},
                ruleCustom: {},
                taskType: [],
                resultData: {},
                taskId: '',
                workFlowList: [
                    {text: '隐患上报流程'},
                    {text: '三、四级隐患排查流程'},
                    {text: '二级隐患排查流程'},
                    {text: '一级隐患排查流程'},
                    {text: '监督检查隐患整改通知单'},
                    {text: '事故简报二级审批流程'},
                    {text: '事故简报三级审批流程'},
                    {text: '事件报告审批流程'},
                    {text: '企业安全总监推荐流程'},
                    {text: '企业安全总监变更流程'},
                    {text: '作业方案三级管理流程'},
                    {text: '作业方案二级管理流程'},
                    {text: '作业方案一级管理流程'},
                    {text: '作业方案特级管理流程'},
                    {text: '相关方业绩流程'},
                    {text: '现场审核验收总结流程'},
                    {text: '安全行政处罚表审批流程'},
                    {text: '企业调查报告流程'},
                    {text: '环保问题整改流程'},
                ],
                columns3: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                    },
                    {
                        title: '变更节点',
                        key: 'taskName',
                        align: 'center',
                    },
                    {
                        title: '变更前审批人',
                        key: 'oldUserName',
                        align: 'center',
                    },
                    {
                        title: '变更后审批人',
                        key: 'newUserName',
                        align: 'center',
                    },
                ],
                historyChange: []
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight  - 215;
            // this.pagedata = this.$route.meta.pagedata;
            this.query();
        },
        methods:{
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            reset(){
                this.form1.se_date = [];
                this.form1.userName = "";
                this.form1.procinstName = '';
                this.query();
            },
            query() {
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    orgId: sessionStorage('userId').getObject('userId').companyId
                }
                if(this.form1.se_date.length!=0){
                    if(this.form1.se_date[0] != '' && this.form1.se_date[1] != ''){
                        data.startDate = this.formatDate(new Date(this.form1.se_date[0]), 'yyyy-MM-dd');
                        data.endDate = this.formatDate(new Date(this.form1.se_date[1]), 'yyyy-MM-dd');
                    }
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.form1)));
                let url = Api.getTaskList;
                this.loading = true;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.dataTable.map(item=>{
                        if(item.procinstState =='0' || item.procinstState ==null){
                            item.procinstStateName = '未上报';
                        }else if(item.procinstState =='1'){
                            item.procinstStateName = '已上报';
                        }else if(item.procinstState =='2'){
                            item.procinstStateName = '被退回';
                        }else if(item.procinstState =='3'){
                            item.procinstStateName = '已审批';
                        }
                    })
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            showHistory(row) {
                this.historyModal = true;
                this.loading2 = true;
                this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
                    this.history = res.data;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                });
                this.$http.get(Api.getHistory + '/change/' + row.procinstId, {params: {}}).then((res) => {
                    this.historyChange = res.data;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                });

            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            shopWorkflow(data){
                this.$Modal.confirm({
                    title: '终止流程',
                    content: '<p>确定终止该流程</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.get(Api.shopWorkflow, {params:{
                                procInstId: data.procinstId,
                            }}).then((res) => {
                                if(data.type == "zyxk")
                                    this.$http.get(Api.updatePtwPlanToInit + data.workId).then(res1=>{})
                                this.$Message.success({content:'终止流程成功',duration: 4});
                                this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            flowRemedy(data){
                this.form1data= {};
                this.form1data.formKey = data.formKey;
                this.form1data.taskName = data.taskName;
                this.form1data.workId = data.workId;
                this.$http.get(Api.getRemedy + '/'+ data.procinstId ,{
                    params:{}
                }).then((res) => {
                    this.taskType = res.data.data;
                    this.resultData = res.data;
                    this.model3 = true;
										this.loading3 = false
                }).catch( e => {
                    this.$Message.error('请求失败');
                })
            },
            setPeople(user){
                this.form1data.newUserId = user.userId;
                this.form1data.newUserName = user.userName;
                this.usersListModal = false;
            },
            closeDialog(){
                this.usersListModal = false;
            },
            openSelect(){
                  this.usersListModal = true;
            },
            setOrgname(data){
                this.form1data.newUserId = data[data.length - 1];
            },
            changeType(val) {
                let type = this.form1data.oldUserId;
                if(this.resultData[type] != undefined) {
                    this.form1data.oldUserName = this.resultData[type].userName;
                    this.taskId =  this.resultData[type].taskId;
                }else{
                    this.taskType.forEach(i=>{
                        if(i.label == val.label){
                            this.taskId = i.taskId;
                        }
                    })
                }
            },
            assignSubmit(){
                if( this.form1data.newUserId ==  this.form1data.oldUserId){
                    this.$Message.error('不支持委办给本人，请修改！');
                    return;
                }
                let data = {
                    oldUserId : this.form1data.oldUserId,
                    newUserId : this.form1data.newUserId
                };
                this.$refs['formCustom'].validate((valid) => {
                    if(valid) {
                        this.loading3 = true;
                        this.$http.get(Api.getAssign + this.taskId , {params : data}).then((res) => {
                            this.model3 = false
                            this.$Message.success('补救成功');
                          this.query();
                          if(res.data.status == 200){
                            if (this.form1data.formKey == 'briefingListForApproval'){
                              let brief = {briefId:this.form1data.workId};
                              if (this.form1data.taskName == '企业负责人审批'){
                                brief.chargeId = this.form1data.newUserId;
                                brief.charge = this.form1data.newUserName;
                              }else if (this.form1data.taskName == '二级集团安全环保管理人员审批'){
                                brief.secondaryGroupPersionId = this.form1data.newUserId;
                                brief.secondaryGroupPersion = this.form1data.newUserName;
                              }else if(this.form1data.taskName == '集团安全环保管理人员审批'){
                                brief.groupPersionId = this.form1data.newUserId;
                                brief.groupPersion = this.form1data.newUserName;
                              }
                              let url = Api.briefing;
                              brief.updateUserId = sessionStorage('userId').getObject('userId').userId
                              brief.updateOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                                this.loading3 = false;
                                this.$http.put(url, brief).then((res) => {
                              }).catch(e => {
                                this.$Message.error('请求失败');
                                    this.loading3 = false;
                              })
                            }
                          }
                        }).catch(e => {
                            this.$Message.error('请求失败'+e);
                            this.loading3 = false;
                        });
                    }
                });
            },
            canal(){
                this.model3 = false;
            },
            showData(row){
                let user = sessionStorage('userId').getObject('userId');
                let formKey = row.formKey;
                let data = {
                    taskName:row.taskName,
                    taskId : row.taskId,
                    workId: row.workId,
                    procinstId : row.procinstId,
                    close: false,
                    userId : user.userId,
                    viewFlag: true,
                    status: 'done'
                }
                this.$router.push({ path: "/"+ formKey +'1', query: data});
                // this.path = "/" + formKey + "1";
                // this.model4 = true;
            },
            switchQuery(flag){
                this.switchFlag = flag;
                if(this.switchFlag) {
                    this.tableHeight = this.tableHeight - 44;
                }else{
                    this.tableHeight = this.tableHeight + 44;
                }
            },
        }
    }
</script>

<style scoped>
    @import './../../../index.css';

</style>
